<template>
  <el-upload :limit="5" action="#" list-type="picture-card" :on-exceed="handleExceed" v-model:file-list="fileList"
    :on-change="uploadImg" :auto-upload="false" accept="image/jpg,image/jpeg,image/png,image/webp">
    <el-icon>
      <Plus />
    </el-icon>

    <template #file="{ file }">
      <div>
        <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
        <span class="el-upload-list__item-actions">
          <!-- <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
            <el-icon><zoom-in /></el-icon>
          </span> -->
          <span class="el-upload-list__item-delete" @click="handleRemove(file)">
            <el-icon>
              <Delete />
            </el-icon>
          </span>
        </span>
      </div>
    </template>
    <!-- <template #tip>
      <div class="el-upload__tip"> 可以上传5张照片，单个不超过10M </div>
    </template> -->
  </el-upload>

  <el-dialog append-to-body v-model="dialogVisible">
    <img width="100%" :src="state.dialogImageUrl" alt="" />
  </el-dialog>
</template>
<script setup>
import { ElMessage } from 'element-plus';
import { uploadGame } from "@/api/business/game";
const emit = defineEmits();

let dialogVisible = ref(false);
let fileList = reactive([]);
const state = reactive({
  photoList: [],
  dialogImageUrl: '',
})

// 上传文件
const uploadImg = (file) => {
  // 单个文件大小不能超过50M
  let fileSize = file.size / 1024;
  let maxSize = 1024 * 50;
  if (fileSize > maxSize) {
    ElMessage({
      message: '单个文件最大50M',
      type: 'warning',
    });
    return;
  }
  let rawFile = file.raw;

  let formData = new FormData();
  formData.append('file', rawFile);
  // 调用封装好的接口
  uploadGame(formData).then((res) => {
    if (res.code == 200) {
      ElMessage({
        type: 'success',
        message: '上传成功',
      });
      // 此处 res 的格式为{ fileName: '奥黛丽赫本', fileUrl: '/xxx' }
      state.photoList.push(res.data);
      emit("update:modelValue", state.photoList);
    } else {
      ElMessage({
        type: 'error',
        message: '上传失败',
      });
    }

  });
};

// 删除
const handleRemove = (file) => {
  const index = fileList.indexOf(file);
  fileList.splice(index, 1);
  state.photoList = state.photoList.filter((item) => item.fileName !== file.name);
};

// 预览
const handlePictureCardPreview = (file) => {
  state.dialogImageUrl = file.url;
  dialogVisible.value = true;
};

// 上传照片超出限制的提示
const handleExceed = () => {
  ElMessage({
    message: '最多上传5张照片',
    type: 'warning',
  });
};
</script>